package me.flyray.biz.thymeleaf.thymeleaf;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.github.wxiaoqi.security.biz.common.qr.request.ThymeleafPayRequest;
import com.github.wxiaoqi.security.common.util.AuthUtil;
import com.github.wxiaoqi.security.common.util.EntityUtils;

import net.sf.json.JSONObject;

@Controller
public class ThymeleafPay {
	
	public Logger logger = LoggerFactory.getLogger(getClass());
	
	@Value("${mini.appid}")
	private String miniAppid;
	
	@Value("${mini.secret}")
	private String miniSecret;
	
	@Value("${dopay.url}")
	private String dopayUrl;
	
	/**
	 * 跳转支付页
	 * @param model
	 * @return
	 */
	@GetMapping("/dopay")
	public String dopay(@ModelAttribute ThymeleafPayRequest request, Model model) {
		
		logger.info("微信获取用户信息请求参数。。。。。。。{}", EntityUtils.beanToMap(request));
		String code = request.getCode();
		String goodsId = request.getGoodsId();
		String goodsPic = request.getGoodsPic();
		String goodsPrice = request.getGoodsPrice();
		String platformId = request.getPlatformId();
		String merchantId = request.getMerchantId();
		String openid = null;
		String nickname = null;
		try {
			String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + miniAppid +
					"&secret=" + miniSecret +
					"&code=" + code +
					"&grant_type=authorization_code";
			JSONObject jsonObject = AuthUtil.doGetJson(url);
			openid = jsonObject.getString("openid");
			String token = jsonObject.getString("access_token");
			String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token +
					"&openid=" + openid +
					"&lang=zh_CN";
			JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
			nickname = userInfo.getString("nickname");
			logger.info("微信获取用户昵称。。。。。。。{}", nickname);
			model.addAttribute("openid", openid);
			model.addAttribute("goodsPrice", goodsPrice+"元");
			model.addAttribute("goodsPic", goodsPic);
			model.addAttribute("price", goodsPrice);
			model.addAttribute("goodsId", goodsId);
			model.addAttribute("nickname", nickname);
			model.addAttribute("platformId", platformId);
			model.addAttribute("merchantId", merchantId);
	        return "dopay";
		} catch (Exception e) {
			e.printStackTrace();
			return "pay-fail";
		}
    }
	
	/**
	 * 跳转支付成功页
	 * @param model
	 * @return
	 */
	@GetMapping("/paySuccess")
	public String paySuccess(@ModelAttribute ThymeleafPayRequest request, Model model) {
		model.addAttribute("goodsId", request.getGoodsId());
		model.addAttribute("platformId", request.getPlatformId());
		model.addAttribute("merchantId", request.getMerchantId());
		return "pay-success";
	}
	
	/**
	 * 跳转支付失败页
	 * @param model
	 * @return
	 */
	@GetMapping("/payFail")
	public String payFail(Model model) {
		return "pay-fail";
	}
	
	/**
	 * 跳转页面获取微信code
	 * @param model
	 * @return
	 */
	@GetMapping("/jumpPay")
	public String jumpPay(@ModelAttribute ThymeleafPayRequest request, Model model) {
		try {
			String goodsId = request.getGoodsId();
			String goodsPic = request.getGoodsPic();
			String goodsPrice = request.getGoodsPrice();
			String platformId = request.getPlatformId();
			String merchantId = request.getMerchantId();
			String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + miniAppid +
	                "&redirect_uri=" + URLEncoder.encode(dopayUrl+"?goodsId="+goodsId+
	                "&goodsPic="+goodsPic+"&goodsPrice="+goodsPrice+"&platformId="+platformId+"&merchantId="+merchantId,"UTF-8") +
	                "&response_type=code" + "&scope=snsapi_userinfo" + "&state=STATE#wechat_redirect";
			logger.info("获取微信code:{}",url);
			model.addAttribute("codeUrl", url);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
        return "jump-pay";
    }
	
	/**
	 * 个人二维码支付测试
	 * @param model
	 * @return
	 */
	@GetMapping("/testCreateOrder")
	public String testCreateOrder(Model model) {
		return "test-create-order";
	}
	
	/**
	 * 接口文档
	 * @param model
	 * @return
	 */
	@GetMapping("/document")
	public String document(Model model) {
		return "document";
	}

}
